package com.yan.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.SSOToken;
import com.baomidou.kisso.common.IpHelper;
import com.baomidou.kisso.common.util.HttpUtil;
import com.baomidou.kisso.web.waf.request.WafRequestWrapper;
import com.google.common.collect.Lists;
import com.yan.bean.Diary;
import com.yan.bean.PageBean;
import com.yan.bean.User;
import com.yan.validator.LoginValidator;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.yan.annon.RouterMapping;
//import com.yan.intercepter.LoginInterceptor;
import com.yan.intercepter.SSOJFinalInterceptor;

@RouterMapping(url = "/")
//@Clear(LoginInterceptor.class)

public class IndexController extends Controller {

    Logger log = Logger.getLogger(IndexController.class);

    @Before(SSOJFinalInterceptor.class)
    public void index() {

        SSOToken token = SSOHelper.attrToken(getRequest());
        if (token != null) {
            render("main.jsp");
        } else {
            render("index.jsp");
        }


    }


    public void main() {

        Diary diary = getBean(Diary.class, "");
        PageBean pageBean = new PageBean(0, 10);
        List<Diary> diaryList = Diary.dao.queryDiaryList(pageBean, diary);
//            int total=diaryDao.diaryCount(con,diary);
//            String pageCode=this.genPagation(total, Integer.parseInt(page), Integer.parseInt(PropertiesUtil.getValue("pageSize")));

//            setAttr("pageCode", pageCode);
        setAttr("diaryList", diaryList);
//            setAttr("diaryTypeCountList", diaryTypeDao.diaryTypeCountList(con));
//            setAttr("diaryCountList", diaryDao.diaryCountList(con));       
        setAttr("mainPage", "diary/diaryList.jsp");

        render("main.jsp");
    }


    @Before(LoginValidator.class)
    public void login() {

        SSOToken token = SSOHelper.getToken(getRequest());

        if (token != null) {
            redirect("/");
            return;
        }

        /**
         * 登录 生产环境需要过滤sql注入
         */



            User u = getBean(User.class, "");
            User user = User.dao.getUserByNameAndPwd(u);
            if (user == null) {
                render("index.jsp");
            } else {
                setSessionAttr("currentUser", user);

                Diary diary = getBean(Diary.class, "");
                PageBean pageBean = new PageBean(0, 10);
                List<Diary> diaryList = Diary.dao.queryDiaryList(pageBean, diary);
//            int total=diaryDao.diaryCount(con,diary);
//            String pageCode=this.genPagation(total, Integer.parseInt(page), Integer.parseInt(PropertiesUtil.getValue("pageSize")));

//            setAttr("pageCode", pageCode);
                setAttr("diaryList", diaryList);
//            setAttr("diaryTypeCountList", diaryTypeDao.diaryTypeCountList(con));
//            setAttr("diaryCountList", diaryDao.diaryCountList(con));
                setAttr("mainPage", "diary/diaryList.jsp");


                token = new SSOToken();
                token.setId(1000L);
                token.setUid("1000");

                token.setIp(IpHelper.getIpAddr(getRequest()));

                //记住密码，设置 cookie 时长 1 周 = 604800 秒 【动态设置 maxAge 实现记住密码功能】
                //String rememberMe = req.getParameter("rememberMe");
                //if ( "on".equals(rememberMe) ) {
                //	request.setAttribute(SSOConfig.SSO_COOKIE_MAXAGE, 604800);
                //}

                SSOHelper.setSSOCookie(getRequest(), getResponse(), token, true);

                render("main.jsp");
            }


        render("index.jsp");
    }


    public void loginout() {

        if (getSessionAttr("currentUser") != null) {
            removeSessionAttr("currentUser");
        }
        SSOHelper.clearLogin(getRequest(), getResponse());
        render("index.jsp");

    }


    private String genPagation(int totalNum, int currentPage, int pageSize) {
        int totalPage = totalNum % pageSize == 0 ? totalNum / pageSize : totalNum / pageSize + 1;
        StringBuffer pageCode = new StringBuffer();
        pageCode.append("<li><a href='main?page=1'>��ҳ</a></li>");
        if (currentPage == 1) {
            pageCode.append("<li class='disabled'><a href='#'>��һҳ</a></li>");
        } else {
            pageCode.append("<li><a href='main?page=" + (currentPage - 1) + "'>��һҳ</a></li>");
        }
        for (int i = currentPage - 2; i <= currentPage + 2; i++) {
            if (i < 1 || i > totalPage) {
                continue;
            }
            if (i == currentPage) {
                pageCode.append("<li class='active'><a href='#'>" + i + "</a></li>");
            } else {
                pageCode.append("<li><a href='main?page=" + i + "'>" + i + "</a></li>");
            }
        }
        if (currentPage == totalPage) {
            pageCode.append("<li class='disabled'><a href='#'>��һҳ</a></li>");
        } else {
            pageCode.append("<li><a href='main?page=" + (currentPage + 1) + "'>��һҳ</a></li>");
        }
        pageCode.append("<li><a href='main?page=" + totalPage + "'>βҳ</a></li>");
        return pageCode.toString();
    }


    public void easyui() throws IOException {


        String dayStart = getPara("startDay");


        StringBuilder json = new StringBuilder();
        BufferedReader reader = getRequest().getReader();
        String line = null;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }
        IOUtils.closeQuietly(reader);

        Map<String, Object> param = (Map<String, Object>) JSONObject.parse(json.toString());

        String endDay = null;
        if ((param != null && param.size() > 0)) {
            String startDay = (String) param.get("startDay");
            endDay = (String) param.get("endDay");
        }


        String channelName = getPara("channelName");

        Map<String, Object> map = new LinkedHashMap<String, Object>();

        if (!StringUtils.isEmpty(channelName)) {
            if ("intrajasa".equals(channelName.toLowerCase())) {
                map.put("channelName", "intrajasa");
            }
        } else {

            map.put("channelName", "xendit");
        }

        map.put("flag", "success");
        map.put("time", DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        ArrayList<Map<String, Object>> list = Lists.newArrayList();
        list.add(map);
        Map<String, Object> map1 = new LinkedHashMap<String, Object>();
        map1.put("rows", list);
        renderJson(map1);
    }


}
